package com.axinfu.util.config.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.axinfu.util.DateUtil;
import com.axinfu.util.config.BtgSetPlugin;
import com.axinfu.util.config.callback.CustomAction;
import com.axinfu.util.config.util.BtgSetHelper;
import com.axinfu.util.config.util.BtgSetUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * BtgSetServlet
 *
 * @author zjn
 * @since 2022/3/24
 */
@SuppressWarnings("all")
public class BtgSetServlet extends ResourceServlet {

    private static final String SUCCCODE = "0000";
    private static final String ERRORCODE = "9999";
    private static final String CODE = "code";
    private static final String MSG = "msg";

    private static BtgSetPlugin btgSetPlugin;

    /**
     * 初始化 btgSetPlugin对象
     */
    public static void initBtgSetPlugin() {
        if (btgSetPlugin == null) {
            btgSetPlugin = BtgSetPlugin.getBtgSetPlugin();
        }
    }

    public BtgSetServlet() {
        super("config/static");
    }

    @Override
    public void init() throws ServletException {

    }

    /**
     * query
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject query(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {

        String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_module")
                + " where state <> -1 "
                + "order by state desc,set_name";
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        JSONObject reJson = new JSONObject();
        try {
            conn = btgSetPlugin.getConnection();
            JSONArray arr = new JSONArray();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            while (rs.next()) {
                JSONObject json = new JSONObject();
                fillRs(rs, json, "key_id", "set_code", "set_name", "set_desc", "state");
                arr.add(json);
            }
            reJson.put("data", arr);

            JSONArray array = new JSONArray();
            int i = 0;
            for (CustomAction ca : btgSetPlugin.excuteCallBackList) {
                JSONObject object = new JSONObject();
                object.put("title", ca.getBtnTitle());
                object.put("desc", ca.getDesc());
                object.put("index", i++);
                array.add(object);
            }
            reJson.put("custom", array);

            return succ(reJson);
        } catch (Exception e) {
            e.printStackTrace();
            reJson.put(MSG, "获取参数配置环境失败!");
            return error(reJson);
        } finally {
            BtgSetUtils.closeDb(conn, statement, null, rs);
        }
    }

    /**
     * initEvn
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */
    public JSONObject initEvn(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        //构造参数环境
        BtgSetHelper.getInstance().resetDataBaseEnv();
        //写入默认配置
        BtgSetHelper.getInstance().writeDefaultSet();
        //启用默认配置
        BtgSetHelper.getInstance().initValue();
        return succ(new JSONObject());
    }

    /**
     * 复制默认模板
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject copyDef(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        String setName = params.getString("set_name");
        String setCode = params.getString("set_code");
        String remark = params.getString("remark");

        String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_module")
                + " where set_code='default'";
        Connection conn = btgSetPlugin.getConnection();
        Statement statement = null;
        ResultSet rs = null;
        JSONObject reJson = new JSONObject();
        try {
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            JSONObject json = new JSONObject();
            while (rs.next()) {
                json.put("key_id", rs.getString("key_id"));
            }
            return copyTpl(json.getString("key_id"), setName, setCode, remark);
        } catch (SQLException e) {
            e.printStackTrace();
            reJson.put(MSG, "复制默认模板失败！");
            return error(reJson);
        } finally {
            BtgSetUtils.closeDb(conn, statement, null, rs);
        }
    }

    /**
     * copyTpl
     *
     * @param moduleId moduleId
     * @param setName  setName
     * @param setCode  setCode
     * @param remark   remark
     * @return JSONObject
     */

    private JSONObject copyTpl(String moduleId, String setName, String setCode, String remark) {
        if (exists(setName, setCode)) {
            JSONObject obj = new JSONObject();
            obj.put(MSG, "配置代码或名称已存在！");
            return error(obj);
        }
        String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_module") + " where key_id=?";
        Connection conn = btgSetPlugin.getConnection();
        Statement statement = null;
        PreparedStatement pstms = null;
        ResultSet rs = null;
        JSONObject reJson = new JSONObject();
        try {
            statement = conn.createStatement();
            pstms = conn.prepareStatement(sql);
            pstms.setString(1, moduleId);
            rs = pstms.executeQuery();
            JSONObject json = new JSONObject();
            while (rs.next()) {
                fillRs(rs, json, "key_id", "set_code", "set_name", "set_desc", "state");
            }

            String keyId = UUID.randomUUID().toString().replaceAll("-", "");
            sql = "insert into " + btgSetPlugin.getTabMap().get("btg_set_cfg_module") + "(key_id,set_code,set_name," +
                    "set_desc,state)";
            sql += "values(?,?,?,?,?)";
            pstms = conn.prepareStatement(sql);
            pstms.setString(1, keyId);
            pstms.setString(2, setCode);
            pstms.setString(3, setName);
            pstms.setString(4, remark);
            pstms.setInt(5, 0);
            pstms.execute();
            pstms.clearParameters();

            //保存值
            sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_miv") + " where module_code='" + json.getString("set_code") + "'";
            rs = statement.executeQuery(sql);
            sql = "insert into " + btgSetPlugin.getTabMap().get("btg_set_cfg_miv") + "(key_id,module_id,module_code," +
                    "item_code,item_value,remark,i_time)";
            sql += "values(?,?,?,?,?,?,?)";
            while (rs.next()) {
                String mivId = UUID.randomUUID().toString().replaceAll("-", "");
                pstms = conn.prepareStatement(sql);
                pstms.setString(1, mivId);
                pstms.setString(2, keyId);
                pstms.setString(3, setCode);
                pstms.setString(4, rs.getString("item_code"));
                pstms.setString(5, rs.getString("item_value"));
                pstms.setString(6, rs.getString("remark"));
                pstms.setTimestamp(7, new Timestamp(DateUtil.getNow().getTime()));
                pstms.execute();
                pstms.clearParameters();
            }
            return succ(reJson);
        } catch (SQLException e) {
            e.printStackTrace();
            reJson.put(MSG, "复制或备份模板失败！");
            return error(reJson);
        } finally {
            BtgSetUtils.closeDb(conn, statement, pstms, rs);
        }
    }

    private void fillRs(ResultSet rs, JSONObject json, String keyId, String setCode, String setName,
                        String setDesc, String state) throws SQLException {
        json.put(keyId, rs.getString(keyId));
        json.put(setCode, rs.getString(setCode));
        json.put(setName, rs.getString(setName));
        json.put(setDesc, rs.getString(setDesc));
        json.put(state, rs.getString(state));
    }

    /**
     * exists
     *
     * @param setName setName
     * @param setCode setCode
     * @return boolean
     */

    private boolean exists(String setName, String setCode) {
        String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_module")
                + " where set_name=? or set_code=?";
        Connection conn = null;
        PreparedStatement pstms = null;
        ResultSet rs = null;
        boolean con = false;
        try {
            conn = btgSetPlugin.getConnection();
            pstms = conn.prepareStatement(sql);
            pstms.setString(1, setName);
            pstms.setString(2, setCode);
            rs = pstms.executeQuery();

            while (rs.next()) {
                con = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BtgSetUtils.closeDb(conn, pstms, null, rs);
        }
        return con;
    }

    /**
     * sub
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject sub(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        String keyId = params.getString("module");
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            boolean con = false;
            conn = btgSetPlugin.getConnection();
            if (keyId == null || "".equals(keyId)) {
                int state = 1;
                String bak = params.getString("bak");
                if ("true".equals(bak)) {
                    con = true;
                }

                String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_module")
                        + " where state=" + state;
                statement = conn.createStatement();
                rs = statement.executeQuery(sql);
                while (rs.next()) {
                    keyId = rs.getString("key_id");
                }
            }
            JSONArray re = new JSONArray();
            statement = conn.createStatement();
            if (!con) {
                String sql = "select t.*,i.item_name,i.item_desc,i.data_type,i.group_name from "
                        + btgSetPlugin.getTabMap().get("btg_set_cfg_miv") + " t,"
                        + btgSetPlugin.getTabMap().get("btg_set_cfg_item")
                        + " i where t.item_code=i.item_code and  t.module_id='" + keyId + "' order by index_no";

                rs = statement.executeQuery(sql);
                List<String> moduleList = new ArrayList<String>();
                JSONArray arr = new JSONArray();
                while (rs.next()) {
                    JSONObject json = new JSONObject();
                    fillRs(rs, json, "key_id", "module_id", "module_code", "item_code", "item_value");
                    fillRs(rs, json, "remark", "item_name", "item_desc", "data_type", "group_name");
                    if (!moduleList.contains(json.getString("group_name"))) {
                        moduleList.add(json.getString("group_name"));
                    }
                    arr.add(json);
                }

                for (String s : moduleList) {
                    JSONObject json = new JSONObject();
                    json.put("group_name", s);
                    JSONArray data = new JSONArray();
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject obj = arr.getJSONObject(i);
                        if (obj.getString("group_name").equals(s)) {
                            data.add(obj);
                        }
                    }
                    json.put("data", data);
                    re.add(json);
                }
            } else {
                String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_bak");
                rs = statement.executeQuery(sql);
                String content = "";
                while (rs.next()) {
                    content = rs.getString("content");
                    break;
                }
                re = JSONArray.parseArray(content);
            }
            JSONObject obj = new JSONObject();
            obj.put("key_id", keyId);
            obj.put("re", re);
            return succ(obj);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put(MSG, "获取配置信息失败！");
            return error(obj);
        } finally {
            BtgSetUtils.closeDb(conn, statement, null, rs);
        }
    }

    /**
     * save
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject save(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        String data = params.getString("data");
        JSONArray arr = JSONArray.parseArray(data);
        String keyId = params.getString("key_id");
        Connection conn = null;
        PreparedStatement pstate = null;
        try {
            conn = btgSetPlugin.getConnection();
            String sql = "update " + btgSetPlugin.getTabMap().get("btg_set_cfg_miv")
                    + " set item_value=?,u_time=? "
                    + "where module_id=? and item_code=?";
            for (int i = 0; i < arr.size(); i++) {
                pstate = conn.prepareCall(sql);
                JSONObject tmp = arr.getJSONObject(i);
                pstate.setString(1, tmp.getString("item_value"));
                pstate.setTimestamp(2, new Timestamp(DateUtil.getNow().getTime()));
                pstate.setString(3, keyId);
                pstate.setString(4, tmp.getString("item_code"));
                pstate.execute();
                pstate.clearParameters();
            }
            return succ(new JSONObject());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put(MSG, "保存配置信息失败！");
            return error(obj);
        } finally {
            BtgSetUtils.closeDb(conn, pstate, null, null);
        }
    }

    /**
     * apply
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject apply(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        String keyId = params.getString("key_id");
        Connection conn = null;
        Statement stat = null;
        try {
            conn = btgSetPlugin.getConnection();
            String sql = "update " + btgSetPlugin.getTabMap().get("btg_set_cfg_module") + " set state=0";
            stat = conn.createStatement();
            stat.execute(sql);
            sql = "update " + btgSetPlugin.getTabMap().get("btg_set_cfg_module")
                    + " set state=1 where key_id='" + keyId + "'";
            stat.execute(sql);
            BtgSetHelper.getInstance().initValue(keyId);
            return succ(new JSONObject());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put(MSG, "保存配置信息失败！");
            return error(obj);
        } finally {
            BtgSetUtils.closeDb(conn, stat, null, null);
        }
    }

    /**
     * 删除报表模板
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */
    public JSONObject del(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        String keyId = params.getString("key_id");
        try {
            delTpl(keyId);
            return succ(new JSONObject());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put(MSG, "删除配置信息失败！");
            return error(obj);
        }
    }

    /**
     * 根据id或code来删除模板 true为id false为code
     *
     * @param IdOrCode IdOrCode
     * @throws SQLException SQLException
     */

    private void delTpl(String IdOrCode) throws SQLException {
        Connection conn = btgSetPlugin.getConnection();
        Statement stat = conn.createStatement();
        String sql;
        sql = "delete from  " + btgSetPlugin.getTabMap().get("btg_set_cfg_module")
                + " where key_id='" + IdOrCode + "'";
        stat.execute(sql);
        sql = "delete from " + btgSetPlugin.getTabMap().get("btg_set_cfg_miv")
                + " where module_id='" + IdOrCode + "'";
        stat.execute(sql);
        stat.close();
        conn.close();
    }

    /**
     * 登录
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject login(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        Connection conn = null;
        PreparedStatement pstate = null;
        ResultSet rs = null;
        try {
            String loginId = params.getString("login_id");
            String login_pwd = params.getString("login_pwd");

            conn = btgSetPlugin.getConnection();

            String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_user") + " where login_id=?";

            pstate = conn.prepareCall(sql);
            pstate.setString(1, loginId);
            rs = pstate.executeQuery();
            pstate.clearParameters();

            JSONObject re = null;
            while (rs.next()) {
                re = new JSONObject();
                re.put("login_id", rs.getString("login_id"));
                re.put("login_pwd", rs.getString("login_pwd"));
                re.put("uname", rs.getString("uname"));
                re.put("last_time", rs.getString("last_time"));
                break;
            }

            JSONObject obj = new JSONObject();
            if (re == null) {
                obj.put(MSG, "用户名错误");
                return error(obj);
            } else {
                if (!re.getString("login_pwd").equals(login_pwd)) {
                    obj.put(MSG, "密码错误");
                    return error(obj);
                } else {
                    //更新最后登录时间
                    sql = "update " + btgSetPlugin.getTabMap().get("btg_set_user")
                            + " set last_time=? where login_id=?";
                    pstate = conn.prepareCall(sql);
                    pstate.setTimestamp(1, new Timestamp(DateUtil.getNow().getTime()));
                    pstate.setString(2, loginId);
                    pstate.execute();
                    obj.put(keyName, BtgSetUtils.getKey(System.currentTimeMillis()));
                    obj.put("key", keyName);
                    return succ(obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put(MSG, "保存配置信息失败！");
            return error(obj);
        } finally {
            BtgSetUtils.closeDb(conn, pstate, null, rs);
        }
    }

    /**
     * 将选中配置生成xml文件
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */
    public JSONObject expSet(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        String name = params.getString("name");

        JSONObject re = sub(params, req, resp);

        if (SUCCCODE.equals(re.getString(CODE))) {

            JSONArray arr = re.getJSONArray("re");

            Document doc = null;
            for (int i = 0; i < arr.size(); i++) {
                JSONObject obj = arr.getJSONObject(i);
                String groupName = obj.getString("group_name");
                JSONArray items = obj.getJSONArray("data");
                doc = handlerDocument(doc, groupName, items);
            }
            XMLWriter writer = null;
            JSONObject obj = new JSONObject();
            try {

                // 获取classpath
                String classPath = Objects.requireNonNull(this.getClass().getResource("/")).getPath();

                //实例化输出格式对象
                OutputFormat format = OutputFormat.createPrettyPrint();
                //设置输出编码
                format.setEncoding("UTF-8");
                //创建需要写入的File对象
                File file = new File(classPath + "/" + name + ".xml");
                //生成XMLWriter对象，构造函数中的参数为需要输出的文件流和格式
                writer = new XMLWriter(new FileOutputStream(file), format);
                //开始写入，write方法中包含上面创建的Document对象
                writer.write(doc);
                obj.put("xml_name", file.getName());
            } catch (IOException e) {
                e.printStackTrace();
                obj.put(MSG, "生成xml文件失败！");
                return error(obj);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return succ(obj);
        } else {
            return re;
        }
    }

    /**
     * 生成、追加xml文件
     *
     * @param doc       doc
     * @param groupName groupName
     * @param items     items
     * @return Document
     */
    private Document handlerDocument(Document doc, String groupName, JSONArray items) {
        if (doc == null) {
            doc = DocumentHelper.createDocument();
        }
        Element root = doc.getRootElement();
        if (root == null) {
            root = doc.addElement("config");
        }
        Element group = root.addElement("module");
        group.addAttribute("name", groupName);
        Element el;
        for (int i = 0; i < items.size(); i++) {
            JSONObject obj = items.getJSONObject(i);
            el = group.addElement("param");
            el.addAttribute("code", obj.getString("item_code"));
            el.addAttribute("type", obj.getString("data_type"));
            el.addAttribute("name", obj.getString("item_name"));
            el.addAttribute("desc", obj.getString("item_desc"));
            el.addText(obj.getString("item_value"));
        }
        return doc;
    }

    /**
     * download
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */
    public JSONObject download(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        try {

            String fileName = params.getString("xml_name");

            // 获取classpath
            String classPath = Objects.requireNonNull(this.getClass().getResource("/")).getPath();

            // path是指欲下载的文件的路径。
            File file = new File(classPath + "/" + fileName);
            if (file.exists()) {
                // 取得文件名。
                String filename = file.getName();
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                resp.reset();
                // 设置response的Header
                resp.addHeader("Content-Disposition", "attachment;filename="
                        + new String(filename.getBytes("UTF-8"), "ISO-8859-1"));
                resp.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(
                        resp.getOutputStream());
                resp.setContentType("application/vnd.ms-excel;charset=gb2312");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();

                file.delete();
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 备份配置信息
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject bakSet(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        Connection conn = null;
        Statement stat = null;
        PreparedStatement pstate = null;
        try {
            conn = btgSetPlugin.getConnection();
            stat = conn.createStatement();

            String sql = "truncate table " + btgSetPlugin.getTabMap().get("btg_set_cfg_bak");

            stat.execute(sql);
            JSONObject obj = sub(params, req, resp);

            JSONArray arr = obj.getJSONArray("re");

            sql = "insert into " + btgSetPlugin.getTabMap().get("btg_set_cfg_bak")
                    + "(key_id,i_time,content)"
                    + "values(?,?,?)";
            String keyId = UUID.randomUUID().toString().replaceAll("-", "");
            pstate = conn.prepareStatement(sql);
            pstate.setString(1, keyId);
            pstate.setTimestamp(2, new Timestamp(DateUtil.getNow().getTime()));
            pstate.setString(3, arr.toJSONString());
            pstate.execute();
            obj.put(MSG, "备份成功！");
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put(MSG, "备份配置信息失败！");
            return error(obj);
        } finally {
            BtgSetUtils.closeDb(conn, stat, pstate, null);
        }
    }

    /**
     * 查询备份时间
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject getBakTime(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = btgSetPlugin.getConnection();
            stat = conn.createStatement();
            String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_bak");
            rs = stat.executeQuery(sql);
            String i_time = "";
            while (rs.next()) {
                i_time = rs.getString("i_time");
                break;
            }
            JSONObject obj = new JSONObject();
            obj.put("i_time", i_time);
            return succ(obj);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put(MSG, "恢复备份配置失败！");
            return error(obj);
        } finally {
            BtgSetUtils.closeDb(conn, stat, null, rs);
        }
    }

    /**
     * 从备份中恢复
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */

    public JSONObject recoverSet(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        String keyId = params.getString("module");
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = btgSetPlugin.getConnection();
            stat = conn.createStatement();
            String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_bak");
            rs = stat.executeQuery(sql);

            JSONObject obj = new JSONObject();

            String content = null;
            while (rs.next()) {
                content = rs.getString("content");
                break;
            }
            if (content != null) {
                JSONArray arr = JSON.parseArray(content);
                rebakSet(keyId, arr);
                return succ(obj);
            } else {
                obj.put(MSG, "未找到备份配置记录！");
                return error(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put(MSG, "恢复备份配置失败！");
            return error(obj);
        } finally {
            BtgSetUtils.closeDb(conn, stat, null, rs);
        }
    }

    /**
     * 恢复操作
     *
     * @param moduleId moduleId
     * @param arr      arr
     * @throws SQLException SQLException
     */

    private void rebakSet(String moduleId, JSONArray arr) throws SQLException {
        Connection conn = btgSetPlugin.getConnection();
        PreparedStatement pstate;
        ResultSet rs;

        JSONObject object = new JSONObject();
        for (int i = 0; i < arr.size(); i++) {
            JSONArray data = arr.getJSONObject(i).getJSONArray("data");
            for (int j = 0; j < data.size(); j++) {
                JSONObject obj = data.getJSONObject(j);
                String k = obj.getString("item_code");
                String v = obj.getString("item_value");
                object.put(k, v);
            }
        }

        String sql = "select * from " + btgSetPlugin.getTabMap().get("btg_set_cfg_miv") + " where module_id=?";

        pstate = conn.prepareStatement(sql);
        pstate.setString(1, moduleId);
        rs = pstate.executeQuery();

        sql = "update " + btgSetPlugin.getTabMap().get("btg_set_cfg_miv")
                + " set item_value=?,u_time=? where key_id=?";

        while (rs.next()) {
            String itemCode = rs.getString("item_code");
            String itemValue = rs.getString("item_value");
            String key_id = rs.getString("key_id");

            if (object.containsKey(itemCode)) {
                String v = object.getString(itemCode);
                if (!v.equals(itemValue)) {
                    pstate = conn.prepareStatement(sql);
                    pstate.setString(1, v);
                    pstate.setTimestamp(2, new Timestamp(DateUtil.getNow().getTime()));
                    pstate.setString(3, key_id);
                    pstate.execute();
                }
            }

        }
        rs.close();
        pstate.close();
        conn.close();
    }

    /**
     * 执行自定义按钮
     *
     * @param params params
     * @param req    req
     * @param resp   resp
     * @return JSONObject
     */
    public JSONObject doExcute(JSONObject params, HttpServletRequest req, HttpServletResponse resp) {
        try {
            String idx = params.getString("index");
            CustomAction ca = btgSetPlugin.excuteCallBackList.get(Integer.parseInt(idx));
            ca.getCallBack().callBack();
            return succ(new JSONObject());
        } catch (Exception e) {
            e.printStackTrace();
            return error(new JSONObject());
        }
    }

    /**
     * succ
     *
     * @param reJeson reJeson
     * @return JSONObject
     */
    private JSONObject succ(JSONObject reJeson) {
        reJeson.put(CODE, SUCCCODE);
        if (!reJeson.containsKey(MSG)) {
            reJeson.put(MSG, "请求成功！");
        }
        return reJeson;
    }

    /**
     * error
     *
     * @param reJeson reJeson
     * @return JSONObject
     */
    private JSONObject error(JSONObject reJeson) {
        reJeson.put(CODE, ERRORCODE);
        if (!reJeson.containsKey(MSG)) {
            reJeson.put(MSG, "请求失败！");
        }
        return reJeson;
    }
}
